using System.IO;
using UnityEngine;

//持久化存储
public class PersistentStorage : MonoBehaviour
{
    string savePath;
    void Awake()
    {
        //Application.persistentDataPath 包含持久数据目录的路径
        //Path.Combine 链接两个字符串
        savePath = Path.Combine(Application.persistentDataPath,"saveFile");
    }

    public void Save(PersistableObject o, int version)
    {
         using(//using 语法糖，实际上是try finally语句
        //File.Open方法将打开一个文件，通过FileMode.Create来指定如果不存在则创建文件，或替换已存在的文件。返回一个文件流。
        //BinaryWriter 类用于向流中写入内容
        var writer = new BinaryWriter( File.Open(savePath, FileMode.Create) )
        ){
            writer.Write(-version);//保存时翻转版本号防止与正常数据冲突
            o.Save(new GameDataWriter(writer));
        }
    }

    public void Load(PersistableObject o)
    {
        //读取整个文件进行缓冲
        byte[] data = File.ReadAllBytes(savePath);
        var reader = new BinaryReader(new MemoryStream(data));//创建一个包装数组的MemoryStream实例，然后提供给读取器
        o.Load(new GameDataReader(reader, -reader.ReadInt32()));
    }
}